//定义路由
import Vue from 'vue'
import VueRouter from 'vue-router';
Vue.use(VueRouter)

//导入页面组件
import Home from '@/views/Home'
import Topic from '@/views/Topic'
import Category from '@/views/Category'
import Car from '@/views/Car'
import User from '@/views/User'
import Search from '@/views/Search'
import ProductDetail from '@/views/ProductDetail'
import Channel from '@/views/Channel'

//配置路由规则
const routes=[{
    path:'/',
    redirect:'/home',  //重定向
},{
    path:'/home',
    component:Home,
    name:'home',
    meta:{
        isshowtanber:true //meta路由元信息,给当前路由添加一些标记信息
    },
    children:[{
            path:'search', //搜索页定义二级路由
            component:Search,
            meta:{
                isshowtanber:false
            },
        }]
},
{
    path:'/topic',
    component:Topic,
    name:'topic',
    meta:{
        isshowtanber:true
    },
},
,
{
    path:'/category',
    component:Category,
    name:'category',
    meta:{
        isshowtanber:true
    },
},
,
{
    path:'/car',
    component:Car,
    name:'car',
    meta:{
        isshowtanber:true
    },
},
,
{
    path:'/user',
    component:User,
    name:'user',
    meta:{
        isshowtanber:true
    },
},
{
    path:'/ProductDetail',
    component:ProductDetail,
    name:'ProductDetail',
    meta:{
        isshowtanber:false
    },
},
{
    path:'/Channel',
    component:Channel,
    name:'Channel',
    meta:{
        isshowtanber:true
    },
},
]

//创建路由实例对象
const router =new VueRouter({
    mode:'history', //设置路由模式
    routes
})

//创建路由导航前置守卫
router.beforeEach((to,from,next)=>{
    next()
    //如果用户已登录,执行放行
    if(to.path=='/car'){
        //表示访问购物车页
        const token =localStorage.getItem('token'); //返回值要么是字符串要么是空
        if(token){
            //说明本地有token,说明用户已经登录
            next()
        }else{
            //说明没有token,跳转到我的页完成登录
            //先提示先登录.然后5秒提示
            Vue.prototype.$toast({
                type:'fail',
                message:'请先登录',
                duration:500,
            })
            setTimeout(()=>{
                next('/user')
            },1000)
        }
    }
    else{
        //非购物车页直接访问
        
        next()
    }
})

//导出
export default router

